package org.example.translation;

import org.example.baidu_translation.BaiduTranslation;
import org.example.huoshan_translation.HuoshanTranslation;
import org.example.lingvanex_translation.LingvanexTranslation;
import org.example.tencent_translation.TencentTranslation;
import org.example.youdao_translation.YoudaoTranslation;
import org.jetbrains.annotations.Nullable;

import java.util.function.Function;

/**
 * 翻译厂商链条控制
 * 虽然继承了TranslationAble，但仅仅看作是一个代理
 */
public class TranslationManager implements TranslationAble {

    //翻译厂商链条
    private final LangSupportHandler translationHeader;
    //token、ak、sk属性读取
    private final TranslationKeyReader keyReader = new TranslationKeyReader();

    private static TranslationManager instance;

    public static TranslationManager getInstance() {
        if (instance == null) {
            synchronized (TranslationManager.class) {
                if (instance == null) {
                    instance = new TranslationManager();
                }
            }
        }
        return instance;
    }

    /**
     * 读取配置，配置翻译厂商
     */
    private TranslationManager() {
        keyReader.read();
        //火山翻译
        translationHeader = new HuoshanTranslation(keyReader)//火山翻译
                .setNext(new LingvanexTranslation(keyReader)//lingvanex翻译
                        .setNext(new BaiduTranslation(keyReader)//百度翻译
                                .setNext(new YoudaoTranslation(keyReader)//有道翻译
                                        .setNext(new TencentTranslation(keyReader)))));//腾讯翻译
    }

    /**
     * 开始翻译
     * @param postBean 等待翻译数据
     * @return 翻译结果
     */
    @Override
    public @Nullable TranslationResponseBean translation(TranslationPostBean postBean) {
        LangSupportHandler langSupportHandler = translationHeader.process(new LangSupportRequest(postBean.getTargetCountry()));
        if (langSupportHandler == null) {
            new Exception("未找到有效的服务器进行翻译 ---》 " + postBean.getTargetCountry()).printStackTrace();
            return null;
        } else {
            return langSupportHandler.translation(postBean);
        }
    }

}
